
package structure;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;

/**
 * DataCenter reposant sur une structure de type List.
 * 
 * @author David Bernard
 * @since java 1.6
 * @see List
 */
public class ListDataCenter extends AbstractDataCenter
{
	private List<DataNode> list = null;

	/**
	 * Instancie un DataCenter basé sur la structure ArrayList.
	 * 
	 * @see ArrayList
	 */
	public ListDataCenter()
	{
		this(Structure.Vector.name());
	}

	/**
	 * Instancie un DataCenter basé sur la liste entré en paramêtre.
	 * 
	 * @param type String le type de liste.
	 */
	public ListDataCenter(String type)
	{
		boolean ok = this.setListType(type);

		if (!ok)
		{
			throw new RuntimeException("Type de liste invalide");
		}
	}

	private boolean setListType(String nomStructure)
	{
		Structure structure = Structure.trouverAvecNom(nomStructure);
		boolean ok = structure != null;

		if (ok)
		{
			if (structure == Structure.Vector)
			{
				this.list = new Vector<DataNode>();
			}
			else if (structure == Structure.ArrayList)
			{
				this.list = new ArrayList<DataNode>();
			}
			else if (structure == Structure.LinkedList)
			{
				this.list = new LinkedList<DataNode>();
			}
			else
			{
				ok = false;
			}
		}

		return ok;
	}

	@Override
	protected void setElement(DataNode node)
	{
		DataNode temp = null;
		int index = this.list.indexOf(node);

		if (index >= 0)
		{
			temp = this.list.get(index);
			temp.setContenu(node.getContenu());
		}
		else
		{
			this.list.add(node.createNode());
		}
	}

	@Override
	protected DataNode getElement(DataKey referenceNode)
	{
		DataNode node = null;
		int index = this.list.indexOf(referenceNode);

		if (index >= 0)
		{
			node = this.list.get(index);
		}

		return node;
	}

	@Override
	protected void removeElement(DataKey referenceNode)
	{
		int index = this.list.indexOf(referenceNode);

		if (index >= 0)
		{
			this.list.remove(index);
		}
	}

	@Override
	public int size()
	{
		return this.list.size();
	}

	@Override
	public void removeAllData()
	{
		this.list.clear();
		System.gc();
	}

	@Override
	public Iterator<DataNode> iterator()
	{
		return this.list.listIterator();
	}

	/**
	 * Valide le type de structure.
	 * 
	 * @param type String, le type de structure à valider.
	 * 
	 * @return boolean, vrai si valide.
	 */
	public static boolean validerType(String type)
	{
		return (type != null)
				&& (type.equalsIgnoreCase(Structure.Vector.name())
						|| type.equalsIgnoreCase(Structure.LinkedList.name()) || type
							.equalsIgnoreCase(Structure.ArrayList.name()));
	}
}
